#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : BaseEditor(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=TD_CHANGELOG;

    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);

    updateEntry();
    createMenu();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S)
        save();
    else if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Z)
        revert();
    else
    {
        switch (event->key()) {
        case Qt::Key_F1:
            newItem();
            break;
        case Qt::Key_F4:
            updateEntry();
            break;
        case Qt::Key_F5:
            updateView();
            break;
        }
    }
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("新记录... (F1)"),this,&Widget::newItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新列表 (F4)"),this,&Widget::updateEntry);
    menu->addAction(QStringLiteral("更新视图 (F5)"),this,&Widget::updateView);
}

void Widget::updateEntry()
{
    if(listModel->rowCount() != 0)
        listModel->setStringList(QStringList());

    auto items=sp_getCategory("entry",table);
    if(!items.isEmpty())
        listModel->setStringList(items);
}

void Widget::updateView()
{
    if(selectEntry.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("entry='%1'")
                     .arg(selectEntry));
    model->select();
    setHeaderData();
}

void Widget::setHeaderData()
{
    ui->tableView->hideColumn(0);
    ui->tableView->hideColumn(1);   //ENTRY
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("日期"));
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("版本"));
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("变更说明"));
}

void Widget::on_listView_doubleClicked(const QModelIndex &index)
{
    updateView();
}

void Widget::newItem()
{
    AddItem item(this);
    if(!selectEntry.isEmpty())
        item.prepare(selectEntry);

    if(item.exec() == QDialog::Accepted)
        updateView();
}

void Widget::on_listView_clicked(const QModelIndex &index)
{
    selectEntry=index.data().toString();
}
